package com.yami.shop.sys.comment.listener;
import com.google.common.collect.Lists;
import java.util.Date;

import com.yami.shop.bean.enums.PositionType;
import com.yami.shop.bean.event.ShopEmployeeSuperAdminEvent;
import com.yami.shop.bean.event.UpdateShopSuperAdminAccountEvent;
import com.yami.shop.bean.model.ShopDetail;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.service.ShopDetailService;
import com.yami.shop.sys.comment.model.ShopEmployee;
import com.yami.shop.sys.comment.service.ShopEmployeeService;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 秒杀商品状态修改监听
 * @author LGH
 */
@Component("shopEmployeeSuperAdmin")
@AllArgsConstructor
public class ShopEmployeeSuperAdminListener {

    private final ShopEmployeeService shopEmployeeService;
    private final MapperFacade mapperFacade;

    @EventListener(ShopEmployeeSuperAdminEvent.class)
    public void shopEmployeeSuperAdminListener(ShopEmployeeSuperAdminEvent event) {
        ShopDetail shopDetail = event.getShopDetail();
        if (Objects.isNull(shopDetail)) {
            return;
        }
        String mobile = shopDetail.getMobile();
        int count = shopEmployeeService.checkUserName(null, mobile);
        if (count > 0) {
            // 该账号已存在，请重新输入
            throw new YamiShopBindException("yami.store.account.exist");
        }
        ShopEmployee shopEmployee = new ShopEmployee();
        mapperFacade.map(shopDetail,shopEmployee);
        shopEmployee.setType(PositionType.ADMIN.value());
        shopEmployee.setUsername(shopDetail.getMobile());
        shopEmployee.setNickname(shopDetail.getShopName());
        shopEmployee.setStatus(1);
        shopEmployee.setCreateEmployeeId(0L);
        shopEmployeeService.save(shopEmployee);
    }

    @EventListener(UpdateShopSuperAdminAccountEvent.class)
    public void updateShopEmployeeSuperAdminListener(UpdateShopSuperAdminAccountEvent event) {
        ShopDetail shopDetail = event.getShopDetail();
        ShopEmployee shopEmployee = new ShopEmployee();
        mapperFacade.map(shopDetail,shopEmployee);
        shopEmployee.setUsername(shopDetail.getMobile());
        shopEmployeeService.updatePasswordAndUserName(shopEmployee);
    }
}
